package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.dao.LevelDao;
import cc.linker.steplink.crm.domain.Level;
import cc.linker.steplink.crm.merchant.common.PcCouponCustomer;
import cc.linker.steplink.crm.merchant.dao.RightDao;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.service.CustomerIntegralService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.ILevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class LevelServiceImpl implements ILevelService {

    @Autowired
    private LevelDao LevelDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RightDao rightDao;
    @Autowired
    private YzjRequest yzjRequest;
    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;
    @Autowired
    private PcCouponCustomer pcCouponCustomer;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private CustomerIntegralService customerIntegralService;

    @Override
    public List<Map<String, Object>> listLevels(Map map) {
        List<Map<String, Object>> list = LevelDao.listLevels(map);
        if(list!=null && list.size()>0){
            for (Map<String, Object> res : list) {
                res.put("levelBgimage", res.get("levelBgimage").toString());
                res.put("levelOrder", "VIP" + res.get("levelOrder").toString());
                res.remove("orgId");
                String levelId = res.get("levelId").toString();
                //根据levelId获取权益拼接
                String levelBenefits = rightDao.getRightNamesBylevelId(levelId);
                res.put("levelBenefits", levelBenefits);
            }
        }
        return list;
    }

    @Override
    public Boolean addLevel(Map record) throws Exception {
        //添加雅智捷的会员
        if (this.yzjRequest.addMemberInfo((String) record.get("levelName"), (String) record.get("levelId"), (String) record.get("orgId"))) {
            if (1 == LevelDao.addLevel(record)) {
                String levelId = record.get("levelId").toString();
                if (!StringUtils.isEmpty(record.get("rightIds"))) {
                    //添加关联关系
                    String rightIds = record.get("rightIds").toString();
                    List<String> rightlist = Arrays.asList(rightIds.split(","));
                    Map map = new HashMap();
                    map.put("rightlist", rightlist);
                    map.put("levelId", levelId);
                    rightDao.insertLevelRel(map);
                }
                if (!StringUtils.isEmpty(record.get("coupons"))) {
                    List<Map<String, Object>> coupons = (List<Map<String, Object>>) record.get("coupons");
                    if (coupons.size() > 0) {
                        for (Map<String, Object> couponData : coupons) {
                            couponData.put("vipId", levelId);
                            rightDao.insertVipCouponRel(couponData);
                        }
                    }
                }
                Map<String, Object> nextLevelMap = this.LevelDao.getNextLevelInfo(record);
                //如果编辑为0分，把所有没有等级的设置为该等级
                if (Integer.valueOf(record.get("levelScore").toString()).equals(0)) {
                    this.LevelDao.updateCustomerLevelIdByZeroScore(levelId,record.get("orgId").toString());
                } else {
                    Long endScore = null;
                    if (nextLevelMap != null) {
                        endScore = Long.valueOf(nextLevelMap.get("levelScore").toString());
                    }
                    //满足等级的全部设为等级
                    this.customerIntegralService.setCustomersLevelId(Long.valueOf(record.get("levelScore").toString()),
                            endScore,
                            record.get("levelId").toString(),
                            record.get("orgId").toString());

                }
                return true;
            }
        }
        throw GlobalException.build("添加会员等级失败");
    }

    @Override
    public int lastOrder(String orgId) throws Exception {
        Integer lastOrderByOrgId = LevelDao.getLastOrderByOrgId(orgId);
        if (lastOrderByOrgId == null) {
            return 0;
        }
        return lastOrderByOrgId;
    }


    @Override
    public Boolean delLevel(String levelId,String orgId) throws Exception {
        //获取当前等级
        Integer thisOrder = LevelDao.getThisOrder(levelId,orgId);
        if(1 == LevelDao.deleteByPrimaryKey(levelId)){
            //删除送卡券
            rightDao.deleteCouponRelByVipId(levelId);
            //删除关联关系
            rightDao.deleteRelByLevelId(levelId);
            //删除积分商城等级限制
            LevelDao.setIntegralGoods(thisOrder,orgId);
            //获取最大等级id（修改已删除等级的用户）
            String customerLevelId = levelId;
            String newId = LevelDao.getLastLevelId(orgId);
            LevelDao.updateCustomerLevelId(customerLevelId,newId);
            return true;
        }
        return false;
    }

    @Override
    public String getLastLevelId(String orgId) throws Exception {
        return LevelDao.getLastLevelId(orgId);
    }

    @Override
    public Boolean editLevel(Map record,Map oldLevel) throws Exception {
        //添加雅智捷的会员
        if (this.yzjRequest.updateMemberInfo((String) record.get("levelName"), (String) record.get("levelId"), (String) record.get("orgId"))) {
            if (1 == LevelDao.editLevel(record)) {
                String levelId = record.get("levelId").toString();
                //删除关联关系
                rightDao.deleteRelByLevelId(levelId);
                if (!StringUtils.isEmpty(record.get("rightIds"))) {
                    //添加关联关系
                    String rightIds = record.get("rightIds").toString();
                    List<String> rightlist = Arrays.asList(rightIds.split(","));
                    Map map = new HashMap();
                    map.put("rightlist", rightlist);
                    map.put("levelId", levelId);
                    rightDao.insertLevelRel(map);
                }
                //礼包-卡券
                rightDao.deleteCouponRelByVipId(levelId);
                if (!StringUtils.isEmpty(record.get("coupons"))) {
                    List<Map<String, Object>> coupons = (List<Map<String, Object>>) record.get("coupons");
                    if (coupons.size() > 0) {
                        for (Map<String, Object> couponData : coupons) {
                            couponData.put("vipId", levelId);
                            rightDao.insertVipCouponRel(couponData);
                        }
                    }
                }
                //如果所需的成长值变更需要更新用户的当前等级
                if (!record.get("levelScore").toString().equals(oldLevel.get("levelScore").toString())) {
                    //先修改等于这个等级的用户的等级为上一个等级
                    oldLevel.put("orgId", record.get("orgId"));
                    Map<String, Object> preLevelMap = this.LevelDao.getPreLevelInfo(oldLevel);
                    //如果编辑为0分，把所有没有等级的设置为该等级
                    if (Integer.valueOf(record.get("levelScore").toString()).equals(0)) {
                        this.LevelDao.updateCustomerLevelIdByZeroScore(levelId,record.get("orgId").toString());
                    } else {
                        if (preLevelMap != null) {
                            this.LevelDao.updateCustomerLevelId(levelId, preLevelMap.get("levelId").toString());
                        }else {
                            this.LevelDao.removeCustomerLevelId(levelId);
                        }
                        Long startScore = Long.valueOf(record.get("levelScore").toString());
                        Long endScore = null;
                        Map<String, Object> nextLevelMap = this.LevelDao.getNextLevelInfo(oldLevel);
                        if(nextLevelMap!=null && nextLevelMap.containsKey("levelScore")){
                            endScore = Long.valueOf(nextLevelMap.get("levelScore").toString());
                        }
                        //满足新设置到下一等级之间的用户等级的用户设置
                        this.customerIntegralService.setCustomersLevelId(startScore,endScore, record.get("levelId").toString(),record.get("orgId").toString());

                    }
                }
                return true;
            }
        }
        throw GlobalException.build("编辑会员等级失败");
    }

    @Override
    public HashMap<String, Object> getLevelInfo(String levelId,HttpServletRequest request) {
        HashMap<String, Object> levelInfo = LevelDao.getLevelInfo(levelId);
        if(levelInfo!=null && levelInfo.size()>0){
            levelInfo.put("levelBgimage", levelInfo.get("levelBgimage").toString());
            levelInfo.remove("orgId");
            //获取权益id拼接
            String rightIds = rightDao.getRightIdsBylevelId(levelId);
            levelInfo.put("rightIds", rightIds);


            List<Map<String, Object>> vipCoupons = vipCustomerLogDao.getVipCoupons(levelId);
            if(null!=vipCoupons && vipCoupons.size()>0){
                for (int i = vipCoupons.size()-1; i >= 0; i--) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("couponId", vipCoupons.get(i).get("couponId"));
                    Map<String,Object> res = (Map)couponRequest.doRequest("coupon-detail", param, pcCouponCustomer.getCouponCustomerInfo(request));
                    if(null == res || null == res.get("name")){
                        vipCoupons.remove(i);
                    }else{
                        int maxPublishNum = 0;
                        if(null != res.get("maxPublishNum")){
                            maxPublishNum = Integer.parseInt(res.get("maxPublishNum").toString());
                        }
                        int publishNum = 0;
                        if(null != res.get("publishNum")){
                            publishNum = Integer.parseInt(res.get("publishNum").toString());
                        }
                        vipCoupons.get(i).put("name", res.get("name"));
                        vipCoupons.get(i).put("count",maxPublishNum-publishNum);
                    }
                }
//                for(Map<String, Object> vipCoupon:vipCoupons){
//                    Map<String, Object> param = new HashMap<>();
//                    param.put("couponId", vipCoupon.get("couponId"));
//                    Map<String,Object> res = (Map)couponRequest.doRequest("coupon-detail", param, pcCouponCustomer.getCouponCustomerInfo(request));
//                    int maxPublishNum = 0;
//                    if(null!=res && null!=res.get("maxPublishNum")){
//                        maxPublishNum = Integer.parseInt(res.get("maxPublishNum").toString());
//                    }
//                    int publishNum = 0;
//                    if(null!=res && null!=res.get("publishNum")){
//                        publishNum = Integer.parseInt(res.get("publishNum").toString());
//                    }
//                    vipCoupon.put("name", res != null ? res.get("name") : null);
//                    vipCoupon.put("count",maxPublishNum-publishNum);
//                }
            }
            levelInfo.put("coupons", vipCoupons);
        }
        return levelInfo;
    }

    @Override
    public int getLastScore(String orgId) throws Exception {
        Integer lastScore = LevelDao.getLastScore(orgId);
        if (lastScore == null) {
            return -1;
        }
        return lastScore;
    }

    @Override
    public HashMap<String, Object> getPreLevelInfo(Map map) {
        return LevelDao.getPreLevelInfo(map);
    }

    @Override
    public HashMap<String, Object> getNextLevelInfo(Map map) {
        return LevelDao.getNextLevelInfo(map);
    }
}
